import { _decorator, Camera, Component, director, Layers, Node, tween, Vec3 } from 'cc';
import { aaEvent } from '../frame/common/Enums';
const { ccclass, property } = _decorator;
const _tempV3 = new Vec3();

@ccclass('CameraCtrl')
export class CameraCtrl extends Component {
    @property(Camera)
    mainCam:Camera = null;
    private _cam:Camera = null;
    private _orthoHeight = null;
    private _orthoOffset = 0;
    private _pos = new Vec3();
    private _posOffset = 0;

    get orthoOffset(){
        return this._orthoOffset;
    }

    set orthoOffset(num){
        this._orthoOffset = num;
        this._cam.orthoHeight = this._orthoOffset +this._orthoHeight;
    }

    get posOffset(){
        return this._posOffset;
    }

    set posOffset(num){
        this._posOffset = num;
        Vec3.set(_tempV3,this._pos.x+num,this._pos.y+num,this._pos.z);
        this.node.setPosition(_tempV3);
    }

    start() {
        this._cam = this.node.getComponent(Camera);

        if(this.mainCam){
            this.updateCam();
            this.node.parent.on(Node.EventType.SIZE_CHANGED,this.updateCam,this);
            director.on(aaEvent.shakeCam,this.shakeCam,this);
            director.on(aaEvent.vibrateCam,this.vibrateCam,this);
            // director.on(events.blackCam,this.blackCam,this);
        }
    }
    updateCam(){
        this._orthoOffset = this._cam.orthoHeight = this.mainCam.orthoHeight;
        this._pos =  this._cam.node.position = this.mainCam.node.position;
    }
    /**
     * @description: to black out cam
     * @return {*}
     */    
    blackCam(black:boolean){
        this.mainCam.visibility = black? null:Layers.Enum.UI_2D;
    }
     /**
     * @description: to shake cam
     * @return {*}
     */ 
    shakeCam(range:number,time=0.1){
        const self = this.getComponent(CameraCtrl);
        tween(self).to(time,{posOffset:range},{easing:'elasticInOut'}).to(time*0.5,{posOffset:0}).start();
    }
    /**
     * @description: to vibrate cam
     * @return {*}
     */ 
    vibrateCam(range:number,time=0.1){
        const self = this.getComponent(CameraCtrl);
        tween(self).to(time,{orthoOffset:range},{easing:'elasticInOut'}).to(time*0.5,{orthoOffset:0}).start();
    }

   


  
}

